// service/user_service/user_login.go
package user_service

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/ip"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

func (u UserService) UserLogin(c *gin.Context, user models.UserModel) (token string, err error) {
	// 查用户登陆表，是否超过限制
	var userLoginList []models.UserLoginModel
	log := common.GetLog(c)
	// 查生效个数，是不是超过限定的个数
	global.DB.Order("created_at").Find(&userLoginList,
		"user_id = ? and lose = ?", user.ID, false)
	if len(userLoginList) >= global.Config.SiteInfo.Login.UserSimultaneousLoginCount {
		// 超过了限定个数，把最早的那个失效
		loseUserLogin := userLoginList[0]
		oldToken := loseUserLogin.Token
		global.DB.Model(&loseUserLogin).Update("lose", true)
		claims, err := jwts.ParseToken(oldToken)
		if err == nil && claims != nil {
			logrus.Infof("失效token%s", oldToken)
			u.RedisService.SetLogoutToken(ctype.CrowdedLogout, oldToken, claims.ExpiresAt)
		} else {
			log.SetItemError("解下token失败", err)
			logrus.Warnf("解下token失败%s", err)
		}

	}

	// 生成token
	token, err = jwts.GetToken(jwts.ClaimsUserInfo{
		UserID: user.ID,
		Role:   user.Role,
	})
	if err == nil {
		// 设置到用户登陆表中
		_ip := c.ClientIP()
		ua := c.GetHeader("User-Agent")
		addr := ip.GetAddr(_ip)
		global.DB.Create(&models.UserLoginModel{
			UserID: user.ID,
			IP:     _ip,
			Addr:   addr,
			Token:  token,
			UA:     ua,
			Lose:   false,
		})
		c.Request.Header.Set("token", token)
		res.OkWithData(c, token)
		return
	}
	res.FailWithError(c, err)
	return
}
